using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace MFD.SharePoint.TaskNotification
{
    class SPTaskNotificationReceiver : SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {


            SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;

            DeleteJob(webApp);

            //Upgrade existing Notification configuration
            UpgradeNotificationConfig(webApp);

            //Add a notification Timer Job
            CreateJob(webApp);

        }

        private void UpgradeNotificationConfig(SPWebApplication webApp)
        {
              Guid featureID = new Guid(TaskNotification.NOTIFICATION_SITE_FEATURE_GUID);
            //we check all the sites for the notification feature to be enabled.
              foreach (SPSite site in webApp.Sites)
              {
                  SPFeature feature = site.Features[featureID];
                  if (feature != null) //the feature is activated
                  {
                      foreach (SPFeatureProperty prop in feature.Properties)
                      {
                          string listID = prop.Name;
                          TaskNotificationConfig cfg = Utils.Deserialize<TaskNotificationConfig>(prop.Value);


                          //fix configuration for all the v1 configuration 
                          if (cfg.StatusColumnName == null)
                              cfg.StatusColumnName = "Status";
                          if (cfg.AboutToStartStatusChoice == null)
                              cfg.AboutToStartStatusChoice = "Not Started";
                          if (cfg.NotStartedStatusChoice == null)
                              cfg.NotStartedStatusChoice = "Not Started";
                          if (cfg.DueStatusChoice == null)
                              cfg.DueStatusChoice = "In Progress";
                          if (cfg.OverdueStatusChoice == null)
                              cfg.OverdueStatusChoice = "Completed";
                          
                          //we need to update the notification config
                          prop.Value = Utils.Serialize(cfg);

                      }

                  }
                  //we update the feature properties in the database
                  feature.Properties.Update();
              }
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            //TODO: deactivate all the notification feature from all site collections in the current web app.


            
            SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
            
            
            DeleteJob(webApp);
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
            
            //SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;

            ////create the shared persisted object
            //var obj = new NotificationPersistedObject(NotificationPersistedObject.PersitedName, webApp);

            //obj.Update(true); //send it to the config Db and propagate it in the Farm.
            //obj.Provision();
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
            //SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
            
            //// delete the shared persisted object
            //NotificationPersistedObject obj = webApp.GetChild<NotificationPersistedObject>(NotificationPersistedObject.PersitedName);
            //if (obj != null)
            //{
            //    obj.Delete();
            //    obj.Unprovision();
            //}
        }


        private void CreateJob(SPWebApplication webApp)
        {
            string jobName = string.Format("Task Notification for {0}", webApp.Name);

            //Create new Notification Job
            var job = new TaskNotificationJob(jobName, webApp);

            job.Title = jobName;
            //job.Retry = true;
            
            
            //Schedule the job to run every 5 minute
            var schedule = new SPMinuteSchedule();
            
            schedule.BeginSecond = 0;
            schedule.EndSecond=59;
            
            schedule.Interval = 5;
            job.Schedule = schedule;
            
            job.Update(true);
        }

        private void DeleteJob(SPWebApplication webApp)
        {
            //Remove the notification timer job
            foreach (SPJobDefinition job in webApp.JobDefinitions)
            {
                if (job is TaskNotificationJob)
                {
                    job.Delete();
                    job.Unprovision();
                    //job.Update(true);
                    return; //there should be only one per WebApplication
                }
            }
        }
    }
}
